<template>
  <el-scrollbar class="chat-link-page">
    <el-card>
      <div class="card-item">
        <div class="title">聊天链接</div>
        <div class="tips">顾客打开这个界面即刻能够与你的企业进行对话</div>
      </div>
    </el-card>
    <!--<el-card style="margin: 20px 0" v-loading="loading">
      <template #header>
        <div>
          <div class="card-item">
            <div class="title">自定义域名链接地址</div>
            <div class="tips">让对话窗口页面的浏览器地址，显示成自己网址的域名地址</div>
          </div>
        </div>
      </template>
      <div class="chat-link-content">
        <div class="tips-box">
          <p>链接说明：</p>
          <ol>
            <li>下载 <a href="#">自定义链接文件</a></li>
            <li>将文件上传至您服务器的根目录</li>
            <li>在下方输入框中填写您服务器的地址</li>
            <li>点击保存按钮</li>
          </ol>
        </div>

        <el-form :model="form" ref="formRef" label-width="120px" :rules="ruels">
          <el-form-item label="自定义链接接入地址" prop="customDomainNameLink">
            <el-input v-model="form.customDomainNameLink" placeholder="请输入自定义链接接入地址" />
          </el-form-item>
          <el-form-item label="语言" prop="language">
            <el-select
              v-model="form.language"
              placeholder="请选择语言"
              @change="handleChangelanguage"
            >
              <el-option label="中文简体" value="zh"></el-option>
              <el-option label="English" value="en"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="指定分配客服" prop="customerServiceUserid">
            <el-select v-model="form.customerServiceUserid">
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.nickname"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="链接地址">
            <el-input v-model="form.lastlink" disabled></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="sendForm">点击生成</el-button>

            <el-button type="primary" plain @click="copyLink(0)">复制链接</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>-->
    <el-card style="margin: 20px 0" v-loading="loading">
      <template #header>
        <div>
          <div class="card-item">
            <div class="title">默认链接</div>
            <!--<div class="tips">国际站链接仅限中国大陆以外的国家和地区访问</div>-->
          </div>
        </div>
      </template>

      <el-form :model="outForm" ref="outformRef" label-width="120px" :rules="outruels">
        <el-form-item label="语言" prop="language">
          <el-select
            v-model="outForm.language"
            placeholder="请选择语言"
            @change="handleChangelanguage"
          >
            <el-option label="中文简体" value="zh"></el-option>
            <el-option label="English" value="en"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="指定分配客服" prop="customerServiceUserid">
          <el-select v-model="outForm.customerServiceUserid">
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.nickname"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="链接地址">
          <el-input v-model="outForm.lastlink" disabled></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="sendoutForm">点击生成</el-button>

          <el-button type="primary" plain @click="copyLink(1)">复制链接</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card style="margin: 20px 0" v-loading="loading">
      <template #header>
        <div class="card-item">
          <div class="title">自动切换语言</div>
          <div class="tips">顾客在聊天窗口，可以选择适合自己的窗口语言</div>
        </div>
      </template>
      <el-switch v-model="changeLanguage" @change="handleChangeSwitch"></el-switch>
    </el-card>
  </el-scrollbar>
</template>

<script setup>
import {
  onActivated,
  onDeactivated,
  onMounted,
  onUnmounted,
  ref,
  watchEffect,
  shallowRef,
  getCurrentInstance,
  onBeforeUnmount,
  watch,
} from "vue";
import { successMessage, warnMessage, errorMessage } from "@/utils/message";
import { getUserListByCondition } from "@/api/node-admin-api/role.js";
import { addSessionLink } from "@/api/node-admin-api/chat.js";

const outruels = ref({
  customerServiceUserid: [{ required: true, message: "请选择你想要制定的客服", trigger: "blur" }],
  language: [{ required: true, message: "请选择你想要的语言", trigger: "blur" }],
});

const ruels = ref({
  customDomainNameLink: [
    { required: true, message: "请输入你需要自定义的域名链接地址", trigger: "blur" },
  ],
  customerServiceUserid: [{ required: true, message: "请选择你想要制定的客服", trigger: "blur" }],
  language: [{ required: true, message: "请选择你想要的语言", trigger: "blur" }],
});
const changeLanguage = ref(false);
const outForm = ref({
  changeLanguage: "",
  customerServiceUserid: "",
  language: "zh",
  lastlink: "",
  type: 1,
});

const form = ref({
  changeLanguage: "",
  customDomainNameLink: "",
  customerServiceUserid: "",
  language: "zh",
  lastlink: "",
  type: 0,
});

const handleChangelanguage = (val) => {
  if (val == "en") {
    successMessage("提示：等待系统开发完成统一配置");
    form.value = { ...form.value, language: "zh" };
    outForm.value = { ...outForm.value, language: "zh" };
  }
};

onMounted(() => {
  getAllUser();
});

const loading = ref(false);
const options = ref([]);
const getAllUser = () => {
  loading.value = true;
  getUserListByCondition({ limit: 99999, page: 1 })
    .then((res) => {
      if (res.code == 20000) {
        const { records = [] } = res.data;
        options.value = records;
      }
    })
    .finally((res) => {
      loading.value = false;
    });
};

// 示例发送请求的函数
const formRef = ref(null);
const sendForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      const params = {
        ...form.value,
        changeLanguage: changeLanguage.value,
      };
      loading.value = true;
      addSessionLink(params)
        .then((res) => {
          if (res.code == 20000) {
            // const link = `${form.customDomainNameLink}?entId=${res.data.key}&lang=${form.language}`;
            const link = `http://kf.xurj.top/#/chatStudio?entId=${res.data.key}&lang=${form.value.language}`;
            form.value = { ...form.value, lastlink: link };
          }
        })
        .finally((res) => {
          loading.value = false;
        });
    }
  });
};

// 示例发送请求的函数
const outformRef = ref(null);
const sendoutForm = (formData) => {
  outformRef.value.validate((valid) => {
    if (valid) {
      const params = {
        ...outForm.value,
        changeLanguage: changeLanguage.value,
      };
      loading.value = true;
      addSessionLink(params)
        .then((res) => {
          if (res.code == 20000) {
            console.log("-=-=-=res: ", res);
            // const link = `${form.customDomainNameLink}?entId=${res.data.key}&lang=${outForm.language}`;
            // form.value = { ...form.value, lastlink: link };

            const link = `http://kf.xurj.top/#/chatStudio?entId=${res.data.key}&lang=${outForm.value.language}`;
            outForm.value = { ...outForm.value, lastlink: link };
          }
        })
        .finally((res) => {
          loading.value = false;
        });
    }
  });
};

const handleChangeSwitch = (val) => {
  sendForm();
  sendoutForm();
};

const copyLink = (val) => {
  const link = val ? outForm.value.lastlink : form.value.lastlink;
  if (navigator.clipboard && window.isSecureContext) {
    // 只有在安全上下文（HTTPS）中，navigator.clipboard 才可用
    navigator.clipboard
      .writeText(link)
      .then(() => {
        successMessage("文本已复制");
      })
      .catch((err) => {
        errorMessage("复制文本失败");
      });
  } else {
    // 处理不支持 clipboard API 的情况
    successMessage("浏览器不支持复制功能");
  }
  // 模拟复制链接的功能
};

const copyInternationalLink = () => {
  // 模拟复制国际链接的功能
  successMessage("国际链接已复制");
};
</script>

<style lang="scss" scoped>
.chat-link-page {
  padding: 20px;
}

.chat-link-card {
  margin: 10px 0;
}

.card-item {
  display: flex;
  flex-direction: column;
  .title {
    font-size: 16px;
    font-weight: bold;
    color: var(--color-text);
  }

  .tips {
    font-size: 14px;
    padding: 10px 0;
    color: gray;
  }
}

.chat-link-card {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.chat-link-content {
  // padding: 20px;
  .tips-box {
    background-color: var(--color-secondary-bg);
    padding: 10;
    padding: 20px;
    margin-bottom: 20px;
  }
}

.el-divider {
  margin: 20px 0;
}
</style>
